// pages/accounting_voucher_add/accounting_voucher_add.js
let assistObj = {}

let today = wx.$util.formatDate(new Date(), 'yyyy-MM-dd')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEdit: false,
    rid: '',
    table_id: 'all_voucher',
    table_id_row_id: '',
    price: '',
    urlParams: {},

    detlDataObj: {},
    delVouchers: [],              // 编辑时，点击了删除的原数据的凭证id数组


    dateFlag: false,

    voucherId: '',                //
    voucherNo: '',                // 凭证号
    voucherWord: '',              //
    accountPeriod: '',            //
    voucherDate: today,           // 凭证日期
    dfltDate: today,

    fieldList: [
      { field_id: 'abstract_str', label: '摘要', type: 'splc', is_null: true, plc: '请填写摘要', },
      { field_id: 'account_id', label: '会计科目', type: 'picklist', is_null: false, optionList: [], optionId: 'account_id', optionName: 'account_name', isAssist: true, },
      { field_id: 'amount', label: '', type: 'num', precision: 2, is_null: false, plc: '请输入金额', iconSlot: true, },
    ],
    totalFieldList: [
      { field_id: 'debitTotal', label: '借方合计', type: 'splc', is_null: true, },
      { field_id: 'creditTotal', label: '贷方合计', type: 'splc', is_null: true, },
    ],
    totalData: {
      debitTotal: '0.00',
      creditTotal: '0.00',
    },
    validFlag: false,             // 验证标识
    validDataObj: {},             // 验证表单项

    detlRows: [0, ],
    setShows: {
      0: false,
    },
    formData: {
      voucher_row_id: 0,
      abstract_str: '',
      account_id: '',
      amount: '',
      account_direction: '借',
      field_id: 'credit_amount',
    },
    formDataObj: {
      0: {
        voucher_row_id: 0,
        abstract_str: '',
        account_id: '',
        amount: '',
        account_direction: '借',
        field_id: 'credit_amount',
      },
    },
    assistFieldListObj: {},
    assistFormDataObj: {},
    assistValidDataObj: {},
  },

  toggleFlag(e) {
    this.setData({
      dateFlag: !this.data.dateFlag,
    })
  },
  selectDate(e) {
    let oldVal = this.data.voucherDate.split('-'),
        newVal = e.detail.split('-')
    this.setData({
      voucherDate: e.detail,
    })
    if(oldVal[0] === newVal[0] && oldVal[1] === newVal[1]) return
    this.getVoucherNo(e.detail)
  },

  toggleSet(e) {
    let d = e.currentTarget.dataset,
        key = d.pkey,
        flag = d.flag,
        { setShows, } = this.data
    if(flag) {
      Object.keys(setShows).forEach(k => {
        setShows[k] = false
      })
      setShows[key] = flag
      this.setData({
        setShows,
      })
    } else {
      let arr = Object.values(setShows)
      if(arr.includes(true)) {
        Object.keys(setShows).forEach(k => {
          setShows[k] = false
        })
        this.setData({
          setShows,
        })
      }
    }

  },
  blurIpt(e) {
    let val = e.detail.value,
        { pkey, } = e.currentTarget.dataset,
        { formDataObj, } = this.data
    formDataObj[pkey].abstract_str = val
  },
  // 插入
  insertItem(e) {
    let { pidx, } = e ? e.currentTarget.dataset : { pidx: 0, }, // 索引
        { detlRows, setShows, formDataObj, formData, } = this.data,
        item = Math.max(...detlRows),
        key = detlRows[pidx]
    item += 1
    detlRows.splice(pidx + 1, 0, item)
    setShows[item] = false
    setShows[key] = false
    formDataObj[item] = JSON.parse(JSON.stringify(formData))
    if(!e) formDataObj[item].account_direction = '贷'
    this.setData({
      detlRows,
      setShows,
      formDataObj,
    })
  },
  // 删除
  delItem(e) {
    let { pidx, } = e.currentTarget.dataset, // 索引
        { detlRows, setShows, formDataObj, delVouchers, } = this.data,
        key = detlRows[pidx]
    if(detlRows.length === 1) {
      wx.$toast('至少保留一条凭证行')
      setShows[key] = false
      this.setData({
        setShows,
      })
      return
    }

    if(formDataObj[key].voucher_row_id) delVouchers.push(formDataObj[key].voucher_row_id)

    detlRows.splice(pidx, 1)
    delete setShows[key]
    delete formDataObj[key]
    this.setData({
      detlRows,
      setShows,
      formDataObj,
    })

    this.refreshTotal()
  },
  onSwitchChange(e) {
    let val = e.detail,
        { pkey, } = e.currentTarget.dataset,
        { formDataObj, } = this.data
    formDataObj[pkey].account_direction = val ? '借' : '贷'
    formDataObj[pkey].field_id = val ? 'debit_amount' : 'credit_amount'

    this.refreshTotal()
  },
  changeIpt(e) {
    let { field, val, } = e.detail,
        { field_id, optionList, optionId, optionName, } = field,
        { pkey, } = e.currentTarget.dataset,
        { formDataObj, assistFormDataObj, } = this.data,
        oldVal = formDataObj[pkey][field_id]
    if(val === oldVal) return
    if(field_id === 'account_id') {  // 会计科目
      console.log('会计科目');
      this.dealTargetAcct(pkey, field, val, oldVal)
    } else if(field_id === 'amount') {  // 金额，重新进行金额合计
      let assistFormData = assistFormDataObj[pkey]
      if(assistFormData && (!['', formDataObj[pkey][field_id]].includes(val) || (!assistFormData.quantity || !assistFormDataObj.quantity_unit_price))) {
        let { quantity, quantity_unit_price, } = assistFormData
        if(quantity || quantity_unit_price) {
          if(quantity) {
            quantity_unit_price = (val / quantity).toFixed(4)
          } else if(quantity_unit_price) {
            quantity = (val / quantity_unit_price).toFixed(4)
          }
          assistFormData.quantity = quantity
          assistFormData.quantity_unit_price = quantity_unit_price
          this.setData({
            assistFormDataObj,
          })
        }
      }

      formDataObj[pkey][field_id] = val

      this.refreshTotal()
    }
    formDataObj[pkey][field_id] = val
  },
  changeIptAssist(e) {
    let { field, val, } = e.detail,
        { field_id, type, optionList, optionId, optionName, } = field,
        { pkey, } = e.currentTarget.dataset,
        { formDataObj, assistFormDataObj, } = this.data,
        assistFormData = assistFormDataObj[pkey],
        oldVal = assistFormData[field_id],
        quantityOld = assistFormData.quantity,
        priceOld = assistFormData.quantity_unit_price
    assistFormData[field_id] = val
    if(['quantity', 'quantity_unit_price', ].includes(field_id)) {  // 计算金额
      let { quantity, quantity_unit_price, } = assistFormData
      if(quantity !== '' && quantity_unit_price !== '' && (quantity !== quantityOld || quantity_unit_price !== priceOld)) {
        let amountOld = formDataObj[pkey].amount,
            amountNew = quantity * quantity_unit_price
        // if(Number(amountOld) === amountNew) return
        if(amountOld !== '' && Number(amountOld) === amountNew) return
        formDataObj[pkey].amount = amountNew
        this.setData({
          formDataObj,
        })
        this.refreshTotal()
      }
    } else {
      if(val === oldVal) return
      this.setData({
        assistFormDataObj,
      })
    }
  },
  // 更新合计
  refreshTotal() {
    let { formDataObj, } = this.data,
        debitTotal = 0,
        creditTotal = 0
    Object.values(formDataObj).forEach(formData => {
      let { amount, account_direction, } = formData
      if(amount === '') amount = 0
      if(account_direction === '借') debitTotal += amount
      else creditTotal += amount
    })
    this.setData({
      totalData: {
        debitTotal: debitTotal.toFixed(2),
        creditTotal: creditTotal.toFixed(2),
      }
    })
  },
  // 会计科目处理
  dealTargetAcct(pkey, field, val, oldVal) {
    let { assistFieldListObj, assistFormDataObj, formDataObj, } = this.data,
        formData = formDataObj[pkey],
        { optionList, optionId, } = field,
        selItem = null,
        assistFieldList = assistFieldListObj[pkey] || []
    if(val && val === oldVal) return
    optionList.some(opt => {
      if(opt[optionId] === val) {
        selItem = opt
        return true
      }
    })
    if(!selItem) return
    if(selItem.is_assist_account) { // 需要辅助核算
      console.log('需要辅助核算的')
      let rowIds = selItem.assist_account_json.split(','),
          proArr = [],
          arr = []
      rowIds.forEach(rid => {
        // 获取辅助核算要填的几个框的选项
        if(assistObj[rid]) {
          arr.push(assistObj[rid])
          let { table_id, } = assistObj[rid]
          proArr.push(this.getAssistOptions(table_id))
        }
      })
      Promise.all(proArr).then(res => {
        assistFieldList = selItem.is_quantity_account ? [
          { field_id: 'quantity', label: '数量', type: 'num', precision: 4, is_null: true, plc: '请输入数量', },
          { field_id: 'quantity_unit_price', label: '单价', type: 'num', precision: 4, is_null: true, plc: '请输入单价', },
        ] : []
        let obj = selItem.is_quantity_account ? { quantity: '', quantity_unit_price: '', quantity_unit: selItem.quantity_unit, } : {}
        res.forEach((rows, r) => {
          assistFieldList.push({
            field_id: `quantity_account_${r + 1}_row_id`,
            label: arr[r].assist_account,
            type: 'picklist',
            is_null: false,
            optionList: rows,
            optionId: 'row_id',
            optionName: arr[r].field_id,
            assist_account_json: rowIds[r],
          })
          obj[`quantity_account_${r + 1}_row_id`] = ''
        })
        assistFieldListObj[pkey] = assistFieldList
        this.setData({
          assistFieldListObj,
        })

        this.data.assistFormDataObj[pkey] = obj
        if(formData.amount === '' && formData.account_direction !== selItem.account_direction) {
          formData.account_direction = selItem.account_direction
          formData.field_id = selItem.account_direction === '借' ? 'debit_amount' : 'credit_amount'

          this.setData({
            formDataObj,
          })
        }
      })
    } else {  // 不需要辅助核算
      if(!assistFieldList.length) return
      delete assistFieldListObj[pkey]
      delete assistFormDataObj[pkey]
      this.setData({
        assistFieldListObj,
        assistFormDataObj,
      })
    }
  },
  // 记录验证表单项
  validIpt(e) {
    let { pkey, } = e.currentTarget.dataset,
        validData = this.data.validDataObj[pkey]
    this.data.validDataObj[pkey] = {
      ...validData,
      ...e.detail,
    }
  },
  validIptAssist(e) {
    let { pkey, } = e.currentTarget.dataset,
        assistValidData = this.data.assistValidDataObj[pkey]
    this.data.assistValidDataObj[pkey] = {
      ...assistValidData,
      ...e.detail,
    }
  },
  // 保存/保存并新增
  async saveData(e) {
    let { reset, } = e.currentTarget.dataset,
        { detlRows, assistFieldListObj, } = this.data,
        validObj = {},
        assistValidObj = {}

    detlRows.forEach(key => {
      validObj[key] = {}
      if(assistFieldListObj[key]) assistValidObj[key] = {}
    })
    this.data.validDataObj = validObj
    this.data.assistValidDataObj = assistValidObj

    this.setData({
      validFlag: !this.data.validFlag,
    })

    let { validDataObj, assistValidDataObj, formDataObj, assistFormDataObj, totalData, delVouchers, price, } = this.data,
        { debitTotal, creditTotal, } = totalData,
        validArr = []
    Object.values(validDataObj).forEach(val => validArr.push(...Object.values(val)))
    Object.values(assistValidDataObj).forEach(val => validArr.push(...Object.values(val)))
    let msg = ''
    if(validArr.includes(false)) {
      msg = '必填项不能为空'
    } else if(debitTotal !== creditTotal) {
      msg = '录入借贷不平！'
    } else {
      let amount0 = Object.values(formDataObj).filter(obj => !obj.amount)
      if(amount0.length) msg = '金额不能为0！'
    }
    if(msg) {
      wx.$toast(msg)
      return
    }

    if(price && Number(price) !== Number(debitTotal || creditTotal)) {
      wx.$toast(`录入金额${Number(debitTotal || creditTotal)}不等于出纳金额${price}！`)
      return
    }

    wx.showLoading({ mask: true, })
    if(delVouchers.length) {  // 编辑，有删除凭证行的原数据，需要请求删除接口
      for(let i = 0, len = delVouchers.length; i < len; i++) {
        let id = delVouchers[i]
        await this.delVoucherData(id)
      }
    }

    for(let i = 0, len = detlRows.length; i < len; i++) {
      let key = detlRows[i],
          { voucherId, voucherNo, voucherWord, accountPeriod, voucherDate, table_id, rid, } = this.data,
          post = {
            ...formDataObj[key],
          }
      if(!post.voucher_row_id) { // 新增
        post = {
          ...post,
          account_period: accountPeriod,
          data_date: voucherDate,
          row_id: rid || 0,
          table_id,
          voucher_id: voucherId,
          voucher_no: voucherNo,
          // voucher_row_id: 0,
          voucher_word: voucherWord,
        }
      }
      if(assistFormDataObj[key]) {
        post = {
          ...post,
          ...assistFormDataObj[key]
        }
        if(post.quantity === '') post.quantity = 0
        if(post.quantity_unit_price === '') post.quantity_unit_price = 0
      }

      await this.saveVoucherData(post)

      if(i + 1 === len) {
        wx.$toast('保存成功！', 2000).then(() => {
          if(reset) { // 保存并新增
            wx.redirectTo({
              url: '../accounting_voucher_add/accounting_voucher_add',
            })
          } else {  // 保存
            wx.navigateBack({
              delta: 1,
            })
          }
        })
      }
    }
  },

  // 接口
  // 获取会计科目
  getTargetAccountList() {
    let post = {
      page: 1,
      limit: 0,
      oby: 'account_id',
    }
    return new Promise((resolve, reject) => {
      wx.$post(3, 'Account/query_account_last', post).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row,
            { fieldList, } = this.data
        fieldList[1].optionList = rows
        this.setData({
          fieldList,
        })
        resolve()
      })
    })
  },
  // 获取辅助核算项目
  getAssistProject() {
    return new Promise((resolve, reject) => {
      wx.$post(1, 'AllAssistAccount/select_all_assist_account', {}).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        assistObj = {}
        rows.forEach(item => assistObj[item.row_id] = item)
        resolve()
      })
    })
  },
  // 获取辅助核算项目中选项
  getAssistOptions(table_id) {
    let post = {
      limit: 0,
      oby: `${table_id}.row_id desc`,
      page: 1,
      table_id: table_id,
    }
    return new Promise((resolve, reject) => {
      wx.$post(3, 'DynamicQuery/query_dynamic_v3', post).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        resolve(rows)
      })
    })
  },
  // 新增获取默认凭证号
  getVoucherNo(date) {
    let arr = date.split('-'),
        post = {
          account_period: `${arr[0]}${arr[1]}`,
          voucher_word: '',
          user_id: '',
          user_name: '',
        }
    wx.$post(3, 'Voucher/get_voucher_word_no', post).then(res => {
      if(res.errcode !== 0) return
      let row = res.data.row[0]
      this.setData({
        voucherNo: row.voucher_no,
        voucherWord: row.voucher_word,
        accountPeriod: post.account_period,
      })
    })
  },
  // 获取凭证
  getVoucherData() {
    let { voucherId, table_id_row_id, table_id, } = this.data,
        post = {
          row_id: table_id_row_id || 0,
          voucher_id: voucherId,
        }
    if(table_id_row_id) post.table_id = table_id
    wx.$post(3, 'Voucher/query_all_voucher', post).then(res => {
      console.log('获取凭证', res);
      if(res.errcode !== 0) return
      let rows = res.data.row,
          { detlDataObj, fieldList, formData, voucherNo, vorcherWord, accountPeriod, voucherDate, rid, } = this.data,
          detlRows = [],
          setShows = {},
          formDataObj = {},
          jsonStr = JSON.stringify(formData),
          needAssist = {}
      rows.forEach((item, i) => {
        if(!i) {  // 编辑时，不请求 Voucher/get_voucher_word_no 接口，所以 voucherNo、vorcherWord、accountPeriod 需要在此处填充，voucherDate 也需要一致
          voucherNo = item.voucher_no
          vorcherWord = item.voucher_word
          accountPeriod = accountPeriod || item.account_period
          voucherDate = item.data_date
        }

        detlDataObj[i] = item
        detlRows.push(i)
        setShows[i] = false

        let obj = JSON.parse(jsonStr)
        obj = {
          abstract_str: item.abstract_str,
          account_direction: item.account_direction,
          account_id: item.account_id,
          account_period: item.account_period,
          amount: item.amount,
          data_date: item.data_date,
          field_id: item.field_id,
          table_id: item.table_id,
          voucher_id: item.voucher_id,
          voucher_no: item.voucher_no,
          voucher_row_id: item.voucher_row_id,
          voucher_word: item.voucher_word,
          row_id: rid || item.row_id,
        }

        formDataObj[i] = obj

        if(item.quantity_unit || item.quantity_account_1_row_id !== null) {  // 需要填充辅助核算的
          needAssist[i] = {
            acctId: item.account_id,
            detlVal: {
              ...item,
            },
          }
        }
      })

      this.setData({
        detlRows,
        setShows,
        voucherNo,
        vorcherWord,
        accountPeriod,
        voucherDate,
        // formDataObj,
      })

      // 获取辅助核算要填的几个框的选项
      let { optionList, optionId, } = fieldList[1],
          assistFieldListObj = {},
          assistFormDataObj = {},
          proAllArr = []
      Object.entries(needAssist).forEach(([key, obj]) => {
        let val = obj.acctId,
            detlVal = obj.detlVal,
            selItems = optionList.filter(opt => opt[optionId] === val),
            selItem = selItems.length ? selItems[0] : null
        if(selItem && selItem.is_assist_account) {  // 需要辅助核算
          let rowIds = selItem.assist_account_json.split(','),
              proArr = [],
              arr = []
          rowIds.forEach(rid => {
            // 获取辅助核算要填的几个框的选项
            if(assistObj[rid]) {
              arr.push(assistObj[rid])
              let { table_id, } = assistObj[rid]
              proArr.push(this.getAssistOptions(table_id))
            }
          })
          if(proArr.length) {
            let pro = new Promise((resolve, reject) => {
              Promise.all(proArr).then(res => {
                let assistFieldList = selItem.is_quantity_account ? [
                  { field_id: 'quantity', label: '数量', type: 'num', precision: 4, is_null: true, plc: '请输入数量', },
                  { field_id: 'quantity_unit_price', label: '单价', type: 'num', precision: 4, is_null: true, plc: '请输入单价', },
                ] : []
                let assistFormData = {}
                if(detlVal.quantity_unit) {
                  let { quantity, quantity_unit_price, quantity_unit, } = detlVal
                  assistFormData = {
                    quantity,
                    quantity_unit_price,
                    quantity_unit,
                  }
                }
                res.forEach((rows, r) => {
                  let field_id = `quantity_account_${r + 1}_row_id`
                  assistFieldList.push({
                    field_id,
                    label: arr[r].assist_account,
                    type: 'picklist',
                    is_null: false,
                    optionList: rows,
                    optionId: 'row_id',
                    optionName: arr[r].field_id,
                    assist_account_json: rowIds[r],
                  })

                  assistFormData[field_id] = (detlVal[field_id] === null ? '' : detlVal[field_id])
                })
                assistFieldListObj[key] = assistFieldList
                assistFormDataObj[key] = assistFormData

                resolve()
              })
            })
            proAllArr.push(pro)
          }
        }
      })
      if(proAllArr.length) {
        Promise.all(proAllArr).then(res => {
          console.log(assistFieldListObj, assistFormDataObj);
          this.setData({
            assistFieldListObj,
            // assistFormDataObj,
          })

          let timer = setTimeout(() => {
            this.setData({
              assistFormDataObj,
            })
            clearTimeout(timer)
          }, 0)
        })
      }


      let timer = setTimeout(() => {
        this.setData({
          formDataObj,
        })
        this.refreshTotal()
        clearTimeout(timer)
      }, 0)
    })
  },
  // 新增/编辑凭证
  saveVoucherData(post) {
    return new Promise((resolve, reject) => {
      let url = post.voucher_row_id ? 'Voucher/alter_all_voucher' : 'Voucher/create_all_voucher'
      wx.$post(3, url, post).then(res => {
        if(res.errcode !== 0) return
        if(!this.data.voucherId) {
          this.setData({
            voucherId: res.data.row[0].voucher_id,
          })
        }
        resolve()
      })
    })
  },
  // 删除凭证
  delVoucherData(id) {
    return new Promise((resolve, reject) => {
      wx.$post(3, 'Voucher/del_all_voucher', { voucher_row_id: id, }).then(res => {
        if(res.errcode !== 0) return
        resolve()
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    // pages/accounting/edit_voucher.js
    let {
          type,                 // 页面类型 edit|编辑  新增凭证时默认不传参数
          id,                   // 出纳表id(出纳表传、凭证表不传)
          table_id,             // 表id：all_voucher、all_cashier
          table_id_row_id,      // （出纳表传、凭证表不传）
          voucher_id,           // 凭证号(出纳表传，凭证表编辑时传)
          price,                // 出纳金额（出纳表传、凭证表不传）
        } = options,
        isEdit = type && type === 'edit'
    if(isEdit) {
      this.setData({
        isEdit: true,
        voucherId: voucher_id,
        rid: id,
        table_id: table_id || 'all_voucher',
        table_id_row_id,
        price,

        urlParams: options,
      })
    }
    Promise.all([this.getTargetAccountList(), this.getAssistProject()]).then(res => {
      if(isEdit) {
        this.getVoucherData()
      } else {
        this.getVoucherNo(today)
        // 221114 插入一个贷的凭证
        this.insertItem()
      }
    })


    // this.getTargetAccountList()
    // this.getAssistProject()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})
